<template>
  <view class="container">
    <view class="header">
      <view class="title">全部资源</view>
      <view class="icons">
        <button class="icon-btn" @click="switchView(currentView === 'list' ? 'grid' : 'list')">
          <svg viewBox="0 0 24 24" v-if="currentView === 'list'">
            <path d="M3 3h7v7H3V3zm0 11h7v7H3v-7zm11 0h7v7h-7v-7zm0-11h7v7h-7V3z"/>
          </svg>
          <svg viewBox="0 0 24 24" v-else>
            <path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"/>
          </svg>
        </button>
        <button class="icon-btn" @click="switchView('search')">
          <svg viewBox="0 0 24 24">
            <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
          </svg>
        </button>
      </view>
    </view>

    <!-- 动态渲染资源 -->
    <view v-for="(items, date) in processedResources" :key="date" class="date-section">
      <view class="date-header">
        <view class="date-badge">{{ date }}</view>
      </view>
      <view class="resources-list" :class="currentView + '-view'">
        <template v-for="(item, index) in items">
          <!-- 渲染广告组件 -->
          <view v-if="item.isAd" class="ad-container" :key="`ad-${date}-${index}`">
            <ad unit-id="你的广告位ID"  
              ad-type="banner"
              :ad-intervals="30"
              @load="onAdLoad"
              @error="onAdError"
              class="banner-ad"
            ></ad>
          </view>
          
          <!-- 渲染资源卡片 -->
          <view v-else class="resource-card" :class="currentView + '-view'" :key="`resource-${item.id}`">
            <image :src="item.iconClass" :alt="item.title" class="card-image" mode="aspectFill"></image>
            <view class="card-content" @click="navigateToDetails(item.id)">
              <view class="card-title">{{ item.title }}</view>
              <view class="card-description">{{ item.description }}</view>
              <view class="card-meta">
                <view class="price-tag" >免费</view>
                <view class="date-text">{{ item.date }}</view>
              </view>
            </view>
          </view>
        </template>
      </view>
    </view>
    
    <!-- 滚动加载提示 -->
    <view v-if="loading" class="scroll-loading">
      <view class="loading">
        <view class="loading-spinner"></view>
        加载中...
      </view>
    </view>
    
    <view v-if="!hasMore && !isEmpty" class="no-more-data">
      已加载全部资源
    </view>
    
    <view v-if="isEmpty && !loading" class="no-more-data">
      暂无资源数据
    </view>
  </view>
</template>

<script>
import {getAllProject} from '@/api/allresources'        

export default {
  data() {
    return {
      currentView: 'list',
      rawResources: {},
      pageNum: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      hasMore: true,
      isEmpty: false,
      isFirstLoad: true,
	  searchKeyword:''
    };
  },
  computed: {
    processedResources() {
      const result = {};
      for (const [date, items] of Object.entries(this.rawResources)) {
        result[date] = [];
        items.forEach((item, index) => {
          result[date].push(item);
          if ((index + 1) % 8 === 0) {
            result[date].push({ isAd: true });
          }
        });
      }
      return result;
    }
  },
  onLoad(options) {
	  this.categoryId = options.categoryId
	  console.log(this.categoryId)
	  this.title = options.title
	  console.log(this.title)
	  this.loadResources();
    // 添加滚动监听
    uni.pageScrollTo({
      scrollTop: 0,
      duration: 0
    });
  },
  onPageScroll(e) {
    this.handleScroll(e);
  },
  methods: {
	  
	  
    navigateToDetails(projectId) {
     console.log(projectId)
     uni.navigateTo({
       url: `/pages/project/project?projectId=${projectId}`
     })
    },
    
    async loadResources() {
      if (this.loading || !this.hasMore) return;
      
      this.loading = true;
      try {
        const res = await getAllProject({
          pageNum: this.pageNum,
          pageSize: this.pageSize,
		  categoryId:this.categoryId,
		  title:this.title
		  
        });
        console.log(res)
        if (res.code === 200) {
          // 如果是第一页，直接替换数据
          if (this.pageNum === 1) {
            this.rawResources = res.data;
            this.isEmpty = Object.keys(res.data).length === 0;
          } else {
            // 合并数据
            this.mergeResources(res.data);
          }
          
          this.total = res.total;
          this.hasMore = this.pageNum * this.pageSize < this.total;
          
          // 如果是首次加载，检查是否有数据
          if (this.isFirstLoad) {
            this.isFirstLoad = false;
          }
        } else {
          console.error('数据加载失败:', res);
          uni.showToast({
            title: '数据加载失败，请重试',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取列表失败:', error);
        uni.showToast({
          title: '请求异常，请检查网络',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    mergeResources(newData) {
      for (const [date, items] of Object.entries(newData)) {
        if (this.rawResources[date]) {
          // 如果该日期已存在，合并数组
          this.rawResources[date] = [...this.rawResources[date], ...items];
        } else {
          // 如果日期不存在，直接添加
          this.rawResources[date] = items;
        }
      }
    },
    
    handleScroll(e) {
      // 滚动到底部时加载更多
      const scrollTop = e.scrollTop;
      const windowHeight = uni.getSystemInfoSync().windowHeight;
      const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
      
      // 距离底部200px时触发加载
      if (scrollTop + windowHeight >= scrollHeight - 200 && !this.loading && this.hasMore) {
        this.pageNum++;
        this.loadResources();
      }
    },
    
   switchView(type) {
     if (type === 'search') {
       // 弹出可输入的模态框
       uni.showModal({
         title: '搜索资源',
         editable: true, // 关键：允许用户输入
         placeholderText: '如：项目名称、关键词', // 占位提示（H5/小程序支持）
         success: async (res) => {
           if (res.confirm && res.content) {
             const keyword = res.content.trim();
   
             uni.showToast({
               title: `搜索: ${keyword}`,
               icon: 'none',
               duration: 1500
             });
   
             // ✅ 1. 保存搜索关键词
             this.title = keyword;
   
             // ✅ 2. 重置分页，从第一页开始搜
             this.pageNum = 1;
             this.hasMore = true;
   
             // ✅ 3. 清空旧数据，触发重新加载
             this.rawResources = {};
             this.isEmpty = false;
   
             // ✅ 4. 调用 loadResources 执行真实搜索
             await this.loadResources();
           }
           // 如果点击取消，不做任何事
         },
         fail: (err) => {
           console.error('搜索弹窗失败:', err);
         }
       });
     } else {
       // 切换视图类型（如全部、分类等）
       this.currentView = type;
   
       // ✅ 如果切换视图时需要重置搜索，可以在这里清除 title
       // this.title = ''; // 可选：切换分类时取消搜索状态
   
       // 重置分页并重新加载
       this.pageNum = 1;
       this.rawResources = {};
       this.hasMore = true;
       this.loadResources();
     }
   },
    
    handleAdClick() {
      uni.showToast({
        title: '广告点击：跳转到详情',
        icon: 'none'
      });
      // 这里可以添加实际的广告跳转逻辑
    },
    
    // 广告加载成功回调
    onAdLoad() {
      console.log('广告加载成功');
    },
    
    // 广告加载失败回调
    onAdError(err) {
      console.error('广告加载失败', err);
    }
  }
};
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 25px;
  color: white;
  position: sticky;
  top: 10px;
  z-index: 100;
}

.title {
  font-size: 24px;
  font-weight: 600;
}

.icons {
  display: flex;
  gap: 15px;
}

.icon-btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.icon-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.05);
}

.icon-btn svg {
  width: 20px;
  height: 20px;
  fill: white;
}

.date-section {
  margin-bottom: 30px;
}

.date-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.date-badge {
  background: linear-gradient(135deg, #ff6b6b, #ffa502);
  color: white;
  padding: 5px 15px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
}

/* --- 列表布局 (默认) --- */
.resources-list.list-view {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.resource-card.list-view {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  display: flex;
  align-items: stretch;
}

.resource-card.list-view:hover {
  transform: translateY(-3px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.12);
}

/* 左侧图片 */
.card-image {
  width: 140px;
  flex-shrink: 0;
  height: 100%;
  object-fit: cover;
}

/* 右侧文字内容 */
.card-content {
  flex-grow: 1;
  padding: 18px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  cursor: pointer;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  line-height: 1.4;
}

.card-description {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.card-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.price-tag {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 500;
}

.price-tag.free {
  background: linear-gradient(135deg, #66bb6a 0%, #43a047 100%);
}

.date-text {
  font-size: 12px;
  color: #999;
}

/* --- 网格布局 --- */
.resources-list.grid-view {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.resource-card.grid-view {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.resource-card.grid-view:hover {
  transform: translateY(-3px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.12);
}

.resource-card.grid-view .card-image {
  width: 100%;
  height: 160px;
  flex-shrink: 0;
}

.resource-card.grid-view .card-content {
  flex-grow: 1;
  padding: 15px;
}

.resource-card.grid-view .card-title {
  font-size: 16px;
  margin-bottom: 6px;
}

.resource-card.grid-view .card-description {
  font-size: 13px;
  margin-bottom: 10px;
}

.resource-card.grid-view .card-meta {
  justify-content: flex-start;
  gap: 10px;
}

.resource-card.grid-view .price-tag {
  font-size: 12px;
  padding: 3px 10px;
}

.resource-card.grid-view .date-text {
  font-size: 11px;
}

/* --- 广告样式 --- */
.ad-container {
  margin: 15px 0;
  border-radius: 16px;
  overflow: hidden;
}

.banner-ad {
  width: 100%;
  height: auto;
  min-height: 100px;
}

/* 加载更多 */
.load-more {
  text-align: center;
  padding: 20px;
  color: #666;
}

.load-more-btn {
  background: #667eea;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 20px;
  cursor: pointer;
}

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  display: inline-block;
  width: 20px;
  height: 20px;
  border: 3px solid rgba(102, 126, 234, 0.3);
  border-radius: 50%;
  border-top-color: #667eea;
  animation: spin 1s ease-in-out infinite;
  margin-right: 10px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .card-image {
    width: 120px;
  }
  
  .header {
    padding: 12px 15px;
  }
  
  .title {
    font-size: 20px;
  }
  
  .card-title {
    font-size: 16px;
  }
  
  .card-description {
    font-size: 13px;
  }

  .resources-list.grid-view {
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  }
}

/* 修复图片自适应 */
.card-image {
  object-fit: cover;
}

.resource-card.list-view .card-image {
  width: 140px;
  height: 140px;
}

.resource-card.grid-view .card-image {
  width: 100%;
  height: 160px;
}

/* 滚动加载提示 */
.scroll-loading {
  text-align: center;
  padding: 15px;
  color: #666;
  font-size: 14px;
}

.no-more-data {
  text-align: center;
  padding: 20px;
  color: #999;
  font-size: 14px;
}
</style>
